using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using MEC;

public abstract class BaseDataTool<T> : MonoBehaviour where T : class
{
    protected List<T> data;

    public event Action DataLoaded;

    public void LoadData(string jsonPath)
    {
        // 使用MEC启动协程
        Timing.RunCoroutine(_LoadData(jsonPath));
    }

    private IEnumerator<float> _LoadData(string jsonPath)
    {
        yield return Timing.WaitUntilDone(JsonDataLoader.LoadJson(jsonPath, jsonString =>
        {
            if (jsonString != null)
            {
                data = ParseData(jsonString);
            }
            else
            {
                data = new List<T>();
            }
            Debug.Log($"{typeof(T).Name} count: {data.Count}");
            OnDataLoaded();
        }));
    }

    protected abstract List<T> ParseData(string jsonString);

    protected void OnDataLoaded()
    {
        DataLoaded?.Invoke();
        DataLoaded = null;
    }

    private void OnDestroy()
    {
        DataLoaded = null;
    }

    public List<T> GetData()
    {
        return data;
    }

    public List<string> ParseStringArray(string jsonArray)
    {
        return JsonConvert.DeserializeObject<List<string>>(jsonArray);
    }

    public List<T> ParseObjectArray(string jsonArray, Func<string, T> parseMethod)
    {
        var array = JsonConvert.DeserializeObject<List<string>>(jsonArray);
        var result = new List<T>();
        foreach (var item in array)
        {
            result.Add(parseMethod(item));
        }
        return result;
    }
}